// JavaScript Document
function HistoryStack ()
{
    this.stack = new Array();
    this.current = -1;
    this.stack_limit = 20;
}

HistoryStack.prototype.addResource = function(resource)
{
    if (this.stack.length > 0) {
        this.stack = this.stack.slice(0, this.current + 1);
    }
    this.stack.push(resource);
    while (this.stack.length > this.stack_limit) {
        this.stack.shift();
    }
    this.current = this.stack.length - 1;
    this.save();
};

HistoryStack.prototype.getCurrent = function ()
{
    return this.stack[this.current];
};

HistoryStack.prototype.hasPrev = function()
{
    return (this.current > 0);
};

HistoryStack.prototype.hasNext = function()
{
    return (this.current < this.stack.length - 1
            && this.current > -1);
};

HistoryStack.prototype.go = function(increment)
{
    // Go back...
    if (increment < 0) {
        this.current = Math.max(-1, this.current + increment);
    // Go forward...
    } else if (increment > 0) {
        this.current = Math.min(this.stack.length - 1,
                                this.current + increment);

    // Reload...
    } else {
        location.reload();
    }

    this.save();
};

HistoryStack.prototype.setCookie = function(name, value)
{
    var cookie_str = name + "=" + escape(value);
    document.cookie = cookie_str;
};

HistoryStack.prototype.getCookie = function(name)
{
    if (!name) return '';

    var raw_cookies, tmp, i;
    var cookies = new Array();

    raw_cookies = document.cookie.split('; ');
    for (i=0; i < raw_cookies.length; i++) {
        tmp = raw_cookies[i].split('=');
        cookies[tmp[0]] = unescape(tmp[1]);
    }
    if (cookies[name] != null) {
        return cookies[name];
    } else {
        return '';
    }
};

HistoryStack.prototype.save = function()
{
    this.setCookie('CHStack', this.stack.toString());
    this.setCookie('CHCurrent', this.current);
};

HistoryStack.prototype.load = function()
{
    var tmp_stack = this.getCookie('CHStack');
    if (tmp_stack != '') {
        this.stack = tmp_stack.split(',');
    }

    var tmp_current = parseInt(this.getCookie('CHCurrent'));
    if (tmp_current >= -1) {
        this.current = tmp_current;
    }

};